package com.eunion.web.cms.controller;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eunion.common.util.RegUtils;
import com.eunion.core.ExcelUtil;
import com.eunion.core.LogUtil;
import com.eunion.core.exception.ValidateException;
import com.eunion.fileserver.upload.FileInfo;
import com.eunion.web.cms.entity.RecruitStudentsPlan;
import com.eunion.web.cms.entity.ScoreRank;
import com.eunion.web.cms.entity.spec.RecruitStudentsPlanSpec;
import com.eunion.web.cms.service.RecruitStudentsPlanService;
import com.eunion.web.cms.service.ScoreRankService;
import com.eunion.web.common.base.BaseService;
import com.eunion.web.common.base.BaseTableCommonController;

/**
 * 招生计划
 */
@Controller
@RequestMapping("/api/students-plans")
@PreAuthorize("hasAuthority('studentsplan:info')")
public class RecruitStudentsPlanResource extends BaseTableCommonController<RecruitStudentsPlan, Long> {

    @Override
    protected BaseService<RecruitStudentsPlan, Long> getBaseService() {
        return recruitStudentsPlanService;
    }

    @Autowired
    private RecruitStudentsPlanService recruitStudentsPlanService;

    @Autowired
    private ScoreRankService scoreRankService;

    /**
     * 进入招生计划查询页面
     * @return
     */
    @RequestMapping("/index")
    public String index() {
        return getUrlBase();
    }

    @Override
    protected String getUrlBase() {
        return "admin/studentsplan/studentsplan";
    }

    /**
     * 招生计划数据导入
     * @param obj
     * @param result
     * @param model
     * @param request
     * @return
     */
    @PreAuthorize("hasAuthority('studentsplan:import')")
    @PostMapping("/importData")
    public String importData(FileInfo obj, BindingResult result, Model model, HttpServletRequest request) {
        try {
            checkBindResult(result);
            if (StringUtils.isNotBlank(obj.getFilepath())) {
                String filepath = obj.getFilepath();
                String fileType = filepath.substring(filepath.lastIndexOf(".") + 1);
                InputStream in = null;

                Workbook wb = null;
                if (fileType.equals("xls")) {
                    in = new FileInputStream(filepath);
                    wb = new HSSFWorkbook(in);
                } else if (fileType.equals("xlsx")) {
                    in = new FileInputStream(filepath);
                    wb = new XSSFWorkbook(in);
                } else {
                    setModuleStatusError(model, "文件格式错误");
                    setModuleImport(model);
                    return getUrlBase().concat("-import");
                }

                // 上传文件的原始名称
                String fileNameOrg = obj.getFileNameOrg();
                // 方向，1.文科，2.理科
                int direction = 0;
                if (StringUtils.isNotBlank(fileNameOrg)) {
                    if (fileNameOrg.contains("文科")) {
                        direction= 1;
                    } else if (fileNameOrg.contains("理科")) {
                        direction= 2;
                    }
                }
                // 年份
                String year = RegUtils.getNumbers(fileNameOrg);
                // 省份
                String provinceName = fileNameOrg.split("_")[1].replace("省", "").replace("市", "");
                // 去查询得分所在的排名范围
                ScoreRank query = new ScoreRank();
                query.setYear(year);
                query.setProvinceName(provinceName);
                query.setDirection(direction);
                Map<String, String> scoreRankMap = scoreRankService.getScoreRankMap(query);
                
                // 开始解析数据
                Sheet sheet = wb.getSheetAt(0);
                List<RecruitStudentsPlan> list = ExcelUtil.readRecruitPlan(sheet, fileNameOrg, scoreRankMap);

                boolean ret = importUpdate(list);
                if(ret) {
                	setModuleStatusOK(model, "导入成功");
                } else {
                	LogUtil.get(this.getClass()).error("save recruitStudentsPlanList failed");
                    setModuleStatusOK(model, "导入失败");
                }
                /*List<RecruitStudentsPlan> resultList = getBaseService().save(list);
                if (null == resultList || resultList.size() < 1) {
                    LogUtil.get(this.getClass()).error("save recruitStudentsPlanList failed");
                    setModuleStatusOK(model, "导入失败");
                } else {
                    setModuleStatusOK(model, "导入成功");
                }*/
            }
        } catch (ValidateException ve) {
            setModuleStatusError(model, ve.getMsg());
        } catch (Exception e) {
            LogUtil.get(this.getClass()).error("save obj error : {}", e);
            setModuleStatusError(model, "导入失败");
        }
        setModuleImport(model);
        return getUrlBase().concat("-import");
    }

    protected void update(RecruitStudentsPlan fromDB,RecruitStudentsPlan fromFile) {
    	fromFile.setId(fromDB.getId());
    }
    
    protected Specification<RecruitStudentsPlan> getSpecification(RecruitStudentsPlan t){
    	return RecruitStudentsPlanSpec.build(t,true);
    }
}
